import React from 'react';
import ReactDOM from 'react-dom';
import $ from "jquery";

export interface PopoverSearchPanelProps {
    getPopupContainer?: Function;
    content: JSX.Element;
    visible?: boolean;
}

export default class PopoverSearchPanel extends React.Component<PopoverSearchPanelProps, any> {
    popupDom: any;
    componentDidMount() {
        const { getPopupContainer } = this.props;
        let container = document.getElementById("cube-reply-content") || document.body;

        if (typeof getPopupContainer == 'function') {
            container = getPopupContainer();
        }

        this.popupDom = document.createElement("div");
        let top = $(ReactDOM.findDOMNode(this)).offset().top - $(container).offset().top + 23;

        ReactDOM.render(this.renderPopup({
            style: { top }
        }), this.popupDom)

        container.appendChild(this.popupDom);
    }
    componentWillUnmount() {
        if (this.popupDom) {
            $(this.popupDom).remove();
        }
    }
    componentDidUpdate() {
        ReactDOM.render(this.renderPopup({
            style: { top }
        }), this.popupDom)
    }
    renderPopup = ({ style }): JSX.Element => {
        return (
            <div style={{ display: `${this.props.visible ? 'block' : 'none'}`, position: 'absolute', paddingTop: 6, zIndex: 2, ...style }}>
                {this.props.content}
            </div>
        )
    }
    render() {
        return (
            this.props.children as JSX.Element
        )
    }
}